<?php

namespace C\M;

use C\L\Model;
use C\M\GroupBuyingOrder;

class GroupBuyingGoods extends Model
{
    public function beforeValidationOnCreate()
    {
        $this->addtime = $this->uptime = time();
        return true;
    }

    public function beforeValidationOnUpdate()
    {
        $this->uptime = time();
        return true;
    }

    public function updateSales($quantity = 1)
    {
        $this->sales += $quantity;
        return $this->save();
    }

    public function updateStock($quantity = 1)
    {
        $this->stock += $quantity;
        return $this->save();
    }

    public function canBuy($userId, $quantity)
    {
        $otherInfo = json_decode($this->other_info, true);
        if (!$otherInfo['group_buying_limit_quantity']) {
            return true;
        }

        $conditions = 'group_buying_goods_id = :goods_id: AND user_id = :user_id:';
        $column = 'quantity';
        $bind = [
        'user_id'  => $userId,
        'goods_id' => $this->id,
        ];

        switch ($otherInfo['group_buying_limit_type']) {
            case 'by_day':
                $today = date('Y-m-d');
                $startTime = \DateTime::createFromFormat('Y-m-d H:i:s', $today . ' 00:00:00');
                $endTime   = \DateTime::createFromFormat('Y-m-d H:i:s', $today . ' 23:59:59');
                $conditions .= ' AND addtime >= :start_time: AND addtime <= :end_time:';
                $bind['start_time'] = $startTime->getTimestamp();
                $bind['end_time'] = $endTime->getTimestamp();
                break;
            case 'by_user':
                break;
        }

        $sum = GroupBuyingOrder::sum(compact('conditions', 'bind', 'column')) ?? 0;

        return $sum + $quantity <= (int)$otherInfo['group_buying_limit_quantity'];
    }

    public function getSlaveGoodsId()
    {
        $otherInfo = json_decode($this->other_info, true);
        return $otherInfo['slave_goods_id'] ?? null;
    }
}
